/**
 *  ws://127.0.0.1:8000/ws/chat/lobby/
 *  注意：Django端口需要与Websocket地址保持一致
 **/

var username = getUserName();
var room_name = getRoomName();
var chatSocket = CreateWebSocket();

function getRoomName() {
    var pathname = window.location.pathname; // 获取URL的路径部分，如 "/chat/lobby/"
    var parts = pathname.split('/');
    var room_name = parts[parts.length - 2]; // 获取倒数第二个部分，即 "lobby"
    return room_name;
}

function getUserName() {
    var queryString = window.location.search; // 获取查询字符串部分，结果是 "?name=John&age=30"
    var searchParams = new URLSearchParams(queryString); // 创建 URLSearchParams 对象
    var username = searchParams.get('username');
    return username;
}


function CreateWebSocket() {
    const websocket_url = 'ws://' + window.location.host + '/ws/chat/' + room_name + '/';
    var chatSocket = new WebSocket(websocket_url);
    room_name = getRoomName();
    username = getUserName();
    host = window.location.host;
    // 清空聊天框
    document.querySelector('#textarea').value = '';
    console.log(`当前的域名为：${host}`);
    console.log(`用户名名是:${username},房间名是:${room_name}`);
    return chatSocket;
}


// 滚动函数
function roller()
{
    document.querySelector(".content").scrollTop = document.querySelector('.content').scrollHeight;
}

// 发送消息函数
function send() {

    // 发送消息
    let text = document.querySelector('#textarea').value;
    if (!text) {
        alert('请输入内容');
        return;
    }

    //滚动条置底
    roller();

    // 发送消息给消费者
    const message = text;
    chatSocket.send(JSON.stringify({
        // 发送消息和用户名
        'message': message,
        'username': username,
        'room': room_name,
        'type': 'text',
    }));
}


// 处理接收消息
chatSocket.onmessage = function (e) {
    const data = JSON.parse(e.data);
    let item = document.createElement('div');

    // 是否为文本消息
    if (data['type'] === 'text') {

        var text = data.message
        if (!text) {
            alert('请输入内容');
            return;
        }

        // 判断是否为自己发送的消息
        if (data['username'] === username) {
            item.className = 'item item-right';
            item.innerHTML = `<div class="bubble bubble-left">${text}</div><div class="avatar"><img src="http://${host}/static/img/boy.jpg" /></div>`;
        } else {
            item.className = 'item item-left';
            item.innerHTML = `<div class="avatar"><img src="http://${host}/static/img/boy.jpg"/></div><div class="bubble bubble-left">${text}</div>`;
        }


        document.querySelector('.content').appendChild(item);
        document.querySelector('#textarea').value = '';
        document.querySelector('#textarea').focus();


    }
    // 接收消息类型为图片
    else if (data['type'] === 'image') {
        const imageFileName = data['message']; // 图片文件名
        const imageUrl = `http://${host}/media/${imageFileName}`; // 构建图片访问地址
        // 判断是否为自己发送的消息
        if (data['username'] === username) {
            item.className = 'item item-right';
            item.className = 'item item-right';
            item.innerHTML = `<img src="${imageUrl}"  height="30%" width="30%"> <div class="avatar"><img src="http://${host}/static/img/boy.jpg" /></div>`;

        } else {
            item.className = 'item item-right';
            item.className = 'item item-left';
            item.innerHTML = `<div class="avatar"><img src="http://${host}/static/img/boy.jpg"/></div> <img src="${imageUrl}"  height="30%" width="30%">`;

        }

        // 添加到消息框
        document.querySelector('.content').appendChild(item);
        document.querySelector('#textarea').value = '';
        document.querySelector('#textarea').focus();


        // 获取所有的img子元素
        const imgElements = item.querySelectorAll("img");

        // 为每个img子元素添加点击事件监听器
        imgElements.forEach(img => {
            img.addEventListener("click", function () {
                var imgSrc = this.getAttribute("src");
                window.open(imgSrc, "_blank");
            });
        });
    }


    //滚动条置底
    roller();
};


// 处理关闭事件
chatSocket.onclose = function (e) {
    console.error('Chat socket closed unexpectedly');
};


// 当点击发送按钮的时候，处理图片发送
document.getElementById('sendButton').addEventListener('click', function () {
    console.log("发送按钮被点击！")

    const inputElement = document.getElementById('imageInput');
    const file = inputElement.files[0];
    const reader = new FileReader();

    reader.onloadend = function () {
        // Get the Base64 encoded data
        const imageData = reader.result.split(',')[1];
        // Send the image data through WebSocket
        chatSocket.send(JSON.stringify({
            'image': imageData,
            'username': username,
            'room': room_name,
            'type': 'image',
        }));

        console.log('发送成功！');
        inputElement.value = "";
    };

    if (file) {
        reader.readAsDataURL(file);
    } else {
        console.error('Please select an image.');
    }
});


// 点击图片查看，跳转查看大图
window.onload = function () {
    var imgElements = document.getElementsByTagName("img");

    for (var i = 0; i < imgElements.length; i++) {
        imgElements[i].addEventListener("click", function () {
            var imgSrc = this.getAttribute("src");
            window.open(imgSrc, "_blank");
        });
    }
};